// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// c [author] rhyme_lph
// y [email]  rhymelph@gmail.com
// G [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/setting_data_entity.dart';
import 'package:finance_app/src/entities/setting_info_entity.dart';
import 'package:finance_app/src/http_service/http_company_service.dart';
import 'package:finance_app/src/http_service/http_report_service.dart';
import 'package:finance_app/src/http_service/http_setting_service.dart';
import 'package:finance_app/src/mixin/check_plan_mixin.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/widgets/bottom_sheet/date_time_select_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/delete_info_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/got_it_tip_bottom_sheet.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/entities/company_entity.dart';

class GstProvider extends BaseProvider with CheckPlanMixin {
  bool isSelectGst = false;

  String reportingAgency = 'Inland Revenue Authority of Singapore';

  String filingFrequency = 'Quarterly';

  String gstRate = '7%';

  TextEditingController gstNumberController = TextEditingController();
  FocusNode gstNumberFocusNode = FocusNode();

  DateTime gstEffectiveDate;

  @override
  void initState() {
    super.initState();
    isSelectGst = Config.currentCompany.enableGst == 1;
    // reportingAgency = Config.currentCompany.gstAgency??'Inland Revenue Authority of Singapore';
    // filingFrequency = Config.currentCompany.fillingFrequencyText??'Quarterly';
    // gstRate = Config.currentCompany.gstRate??'7%';
    gstNumberController.text =
        Config.currentCompany.gstNumber ?? Config.currentCompany.uen;
    gstEffectiveDate = DateTimeUtils.toDateTime(
        Config.currentCompany.gstEffectiveDate, 'yyyy-MM-dd');
  }

  @override
  void dispose() {
    super.dispose();
    gstNumberController.dispose();
    gstNumberFocusNode.dispose();
  }

  @override
  Future get dataFuture => null;

  void onChangeGstRegister() {
    if (isPlanExpired()) return;
    if (!isSelectGst && !Config.canAccessAdvanceFeature) {
      obtainContext?.call((context) {
        showReadyForUpgradeBottomSheet(context);
      });
      return;
    }

    isSelectGst = !isSelectGst;
    update();
  }

  void onChangeReportingAgency() {}

  void onChangeFilingFrequency() {}

  void onChangeGstRate() {}

  void onChangeGstEffectiveDate() {
    obtainContext?.call((context) async {
      final result = await showDateTimeSelectBottomSheet(
          context, S.current.gst_effective_date, gstEffectiveDate,
          withinFinancialYear: false);
      if (result != null) {
        gstEffectiveDate = result;
        update();
      }
    });
  }

  void onSave() async {
    obtainContext?.call((context) {
      FocusScope.of(context).requestFocus(FocusNode());
    });

    if (gstNumberController.text == null || gstNumberController.text == '') {
      showToast(S.current.please_enter_gst_number);
      return;
    }

    if (gstEffectiveDate == null) {
      showToast(S.current.please_select_gst_effective_date);
      return;
    }

    CompanyEntity companyEntity;
    obtainContext?.call((context) async {
      BaseConfig.dialogBase
          .showLoadingDialog(context: context, text: S.current.loading);
    });
    await post(
        HttpCompanyService.updateCompanies(
          Config.currentCompany.id,
          enable_gst: isSelectGst == true ? 1 : 0,
          gst_number: gstNumberController.text,
          gst_effective_date:
              DateTimeUtils.formatDateTime(gstEffectiveDate, 'yyyy-MM-dd'),
        ),
        autoHandler: AutoHandler.Toast, onSuccess: (result) async {
      companyEntity = getEntityFromResult<CompanyEntity>(result);
      RProvider.myProvider.globalMap[ConfigKey.currentCompany] = companyEntity;
      await RProvider.myProvider.updateGlobalMap();
    });
    await post(HttpReportService.taxSubmissions(),
        autoHandler: AutoHandler.Toast, onSuccess: (result) async {});
    await post(HttpSettingService.getSettingData(),
        autoHandler: AutoHandler.Toast, onSuccess: (result) async {
      RProvider.myProvider.globalMap[ConfigKey.settingData] =
          getEntityFromResult<SettingDataEntity>(result);
      await RProvider.myProvider.updateGlobalMap();
    });
    if (isSelectGst == false) {
      //set none gst as default
      await post(HttpSettingService.updateSettingInfo(tax_id: 1));
    }
    await post(HttpSettingService.getSettingInfo(),
        autoHandler: AutoHandler.Toast, onSuccess: (result) async {
      RProvider.myProvider.globalMap[ConfigKey.settingInfo] =
          getEntityFromResult<SettingInfoEntity>(result);
      await RProvider.myProvider.updateGlobalMap();
    });
    obtainContext?.call((context) async {
      Navigator.of(context).pop();
      if (companyEntity != null) {
        await showInformationUpdateSuccessTipBottomSheet(context);
        Navigator.of(context).pop();
      }
    });
  }
}
